<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>活动详情</el-breadcrumb-item> -->
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="警告：只能选中三级分类" type="warning">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品的分类</span>
          <!-- 选择商品分类级联选择框 -->
          <el-cascader
            v-model="selectdCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTagClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            type="primary"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(i, scope.row)"
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  size="mini"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  @click="removeParams(scope.row.attr_id)"
                  size="mini"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            type="primary"
            >添加属性</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(i, scope.row)"
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  size="mini"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  @click="removeParams(scope.row.attr_id)"
                  size="mini"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        >
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      @close="addDialogClosed"
      :title="titleText"
      :visible.sync="addDialogVisible"
      width="30%"
    >
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      @close="editDialogClosed"
      :title="titleText"
      :visible.sync="editDialogVisible"
      width="30%"
    >
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类列表
      cateList: [],
      //   级联选择框的配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //   选择分配的id
      selectdCateKeys: [],
      //   被激活的名称
      activeName: "many",
      //   动态参数列表
      manyTableData: [],
      // 静态参数列表
      onlyTableData: [],
      //   对话框的显示隐藏
      addDialogVisible: false,
      //   添加表单
      addForm: {
        attr_name: "",
      },
      // 添加表单的校验规则
      addFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      editDialogVisible: false,
      editFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      editForm: {},
      inputVisible: false,
      inputValue: "",
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("获取分类数据失败");
      }
      this.cateList = res.data;
      console.log(res);
      // this.$message.success('获取分类数据失败')
    },
    // 级联选择框变化会触发
    async handleChange() {
      this.getParamsData();
    },
    // tab标签点击处理函数
    handleTagClick() {
      //   console.log("test");
      this.getParamsData();
    },
    // 函数封装
    async getParamsData() {
      if (this.selectdCateKeys.length != 3) {
        this.selectdCateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //   console.log('test');
      //   根据三级分类的id和当前的面板查询数据
      const { data: res } = await this.$http.get(
        "categories/" + this.cateId + "/attributes",
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals.split(",");
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res.data.att);
      console.log(res);

      if (res.meta.status != 200) {
        return this.$message.error("获取商品参数失败");
      }
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
      console.log(res);

      // console.log(this.selectdCateKeys);
    },
    // 监听对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      console.log("close");
    },
    // 点击按钮
    async addParams() {
      console.log("test");
      console.log(this.cateId);
      //  const res= this.$refs.addFormRef.validate(async valid=>{
      //     if(!valid) return

      //   })
      this.$refs.addFormRef.validate((validate) => {
        if (!validate) {
          return;
        }
      });
      const { data: res } = await this.$http.post(
        "categories/" + this.cateId + "/attributes",
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
        }
      );
      console.log(res);

      if (res.meta.status != 201) {
        return this.$message.error("添加分类失败");
      }
      this.$message.success("添加分类成功！");
      this.addDialogVisible = false;
      this.getParamsData();
    },
    // 展示修改分类参数的对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        "categories/" + this.cateId + "/attributes/" + attr_id,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("请求参数失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    async editParams() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) {
          return;
        }
      });
      const { data: res } = await this.$http.put(
        "categories/" + this.cateId + "/attributes/" + this.editForm.attr_id,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改参数列表失败");
      }
      this.$message.success("修改参数列表成功");
      this.getParamsData();
      this.editDialogVisible = false;
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        return this.$message.info("取消了删除");
      }
      const { data: res } = await this.$http.delete(
        "categories/" + this.cateId + "/attributes/" + attr_id
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.error("删除成功！");
      this.getParamsData();
    },
    async handleInputConfirm(row) {
      // if (row.inputValue.trim().length === 0) {
      //   row.inputValue = "";
      //   row.inputVisible = false;
      //   return;
      // }
      row.attr_vals.push(row.inputValue.trim());
      row.inputVisible = false;
      row.inputValue = "";
      // 发起请求
      const { data: res } = await this.$http.put(
        "categories/" + this.cateId + "/attributes/" + row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改参数项失败!");
      }
      this.$message.success("修改成功");
      row.inputVisible = false;
    },
    showInput(row) {
      console.log(row);
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      // ==============
      // 发起请求
      const { data: res } = await this.$http.put(
        "categories/" + this.cateId + "/attributes/" + row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改参数项失败!");
      }
      this.$message.success("修改成功");
      row.inputVisible = false;
    },
  },
  //   如果按钮需要被禁用，则返回true
  computed: {
    isBtnDisabled() {
      if (this.selectdCateKeys.length !== 3) {
        return true;
      }
      console.log("计算");
      return false;
    },
    // 当前选中的三级分类的id值
    cateId() {
      if (this.selectdCateKeys.length === 3) {
        return this.selectdCateKeys[2];
      }
      return null;
    },
    // 动态计算标题的文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>>
